<?php
declare (strict_types=1);

namespace app\user\logic\teacher\admin;

use app\common\exception\LogicException;
use app\user\model\teacher\admin\TeacherLevel as TeacherLevelModel;

/**
 * 讲师等级管理逻辑层
 */
class TeacherLevel extends TeacherLevelModel
{
    /**
     * 获取列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-01
     *
     * @param    [type]                         $map 条件
     * @return   [type]                              [description]
     */
    public function getList(array $map = [])
    {
        return $this->with(['icon_url'])->where($map)->order('update_time', 'DESC')->paginate($this->getListRows());
    }

    /**
     * 创建等级
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-01
     *
     * @param array $data [description]
     * @return   [type]                               [description]
     */
    public function createLevel(array $data)
    {
        // $check = [
        //     'title' => $data['title'],
        //     'icon'  => $data['icon'] ?? 0
        // ];

        // 验证数据
        $this->getValidate()->scene('create')->failException()->check($data);

        // 创建成功
        if (!$this->save($data)) {
            throw new LogicException('新建失败');
        }

        return $this;
    }

    /**
     * 编辑等级
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-01
     *
     * @param    [type]                         $id   [description]
     * @param    [type]                         $data [description]
     * @return   [type]                               [description]
     */
    public function editLevel($id, $data)
    {

        $level = $this->where('id', $id)->findOrFail();

        $check       = $data;
        $check['id'] = $id;
        // 验证数据
        $this->getValidate()->scene('edit')->failException()->check($check);

        $level->title = $data['title'];
        $level->icon  = $data['icon'];
        if (!$level->save()) {
            throw new LogicException('修改失败');
        }

        return $level;
    }

    /**
     * 删除等级
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-01
     *
     * @param    [type]                         $id [description]
     * @return   [type]                             [description]
     */
    public function deleteLevel($id)
    {
        $level = $this->where('id', $id)->findOrFail();

        if (!$level->delete()) {
            throw new LogicException("删除失败");
        }
    }

    /**
     * 获取等级选项
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-27
     *
     * @return   [type]                         [description]
     */
    public function getSelectOptions($mhmId = 0)
    {
        if ($mhmId) {
            return $this->withoutGlobalScope(['mhm'])->where('mhm_id', $mhmId)->field(['id' => 'value', 'title'])->select()->toArray();
        }
        return $this->field(['id' => 'value', 'title'])->select()->toArray();
    }
}
